<template>
  <el-dialog :title="title" :visible.sync="dialogFormVisible" :append-to-body="true" width="65%" @open="handleOpen" @close="handleClose" :close-on-click-modal="false" :close-on-press-escape="false">
    <div @click="hidePool" style="width: 100%; height: 100%;">
      <el-form ref="mainFrom" :model="mainFrom" label-width="120px" :rules="mainRules"  size="small">
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="报告单:" prop="report">
              <el-select v-model="mainFrom.report"  placeholder="报告单" class="w-240" @change="handleGetTableHeader">
                <el-option
                  v-for="item in reportTemplateList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="是否配置算法:" prop="isConfigAlgorithm">
              <el-radio-group v-model="mainFrom.isConfigAlgorithm">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <div @click.stop>
            <el-col :span="10" v-if="mainFrom.report">
              <el-form-item label="参数池:" prop="featurePool" class="featurePool-container">
                <el-input
                class="w-240"
                  @focus="choosePool"
                  readonly
                  placeholder="请选择参数池"
                  v-model="mainFrom.featurePool">
                  <i slot="suffix" class="el-input__icon el-icon-arrow-down"></i>
                </el-input>
              </el-form-item>
            </el-col>
            <!-- 参数池选择 -->
            <div class="featurePool-wrap" v-if="hasPool">
              <div>
                <div class="featurePool-list">
                  <div ref="box" class="scroll-wrap">
                    <el-checkbox-group v-model="featurePoolArray">
                      <el-checkbox :label="item" v-for="(item, index) in featurePoolList" :key="index">
                        {{ item.characteristicName }}
                      </el-checkbox>
                    </el-checkbox-group>
                  </div>
                </div>
                <div class="featurePool-bottom">
                  <el-button size="small" @click="handleCancel">取消</el-button>
                  <el-button type="primary" size="small" @click="handleGetPool">确定</el-button>
                </div>
              </div>
            </div>
          </div>
          <el-col :span="10" v-if="mainFrom.isConfigAlgorithm === 1">
            <el-form-item label="图片算法:" prop="pictureAlgorithm">
              <el-select v-model="mainFrom.pictureAlgorithm"  placeholder="图片算法" class="w-240">
                <el-option
                  v-for="item in pictureAlgorithmList"
                  :key="item.id"
                  :label="item.algorithmName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 参数池指标配置 -->
        <div v-if="tableHeader.length > 0">
          <el-table
          border
          size="small"
          :data="tableData"
          style="width: 100%;height: 300px;overflow-y: auto;">
          <el-table-column
            label="#"
            type="index"
            width="50">
          </el-table-column>
          <el-table-column 
            v-for="(item, index) in tableHeader"
            :key="item.headCode + index"
            :prop="item.headCode"
            :label="item.headName">
            <template slot-scope="scope">
              <div class="norm-config" v-if="item.isRange">
                <span class="config-btn">
                  <i class="el-icon-s-tools config-color" @click="handleConfig(scope.row, item, scope.$index)"></i>
                </span>
                <div class="config-info">
                  <span>范围: {{ scope.row[item.headCode + '_min']}} ~ {{ scope.row[item.headCode + '_max']}}</span>
                </div>
              </div>
              <div class="norm-config" v-else>
                <span>{{ scope.row[item.headCode] }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="80">
            <template slot-scope="scope">
                <span class="delete-btn" @click="handleDelete(scope.row, scope.$index)">删除</span>
            </template>
          </el-table-column>
          </el-table>
        </div>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleSubmitData" :disabled="submitLoading">确 定</el-button>
    </div>
    <!-- 配置指标 -->
    <el-dialog
      width="30"
      title="配置指标"
      :visible.sync="innerVisible"
      append-to-body>
        <el-form ref="quotaFrom" :model="quotaFrom" label-width="120px" :rules="quotaRules"  size="small">
          <el-row :gutter="20">
           <el-col :span="10">
            <el-form-item label="最小值:" prop="minQuota">
              <el-input v-model="quotaFrom.minQuota"></el-input>
            </el-form-item>
           </el-col>
           <el-col :span="10">
            <el-form-item label="最大值:" prop="maxQuota">
              <el-input v-model="quotaFrom.maxQuota"></el-input>
            </el-form-item>
           </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleQuotaClose">取 消</el-button>
          <el-button type="primary" @click="handleQuotaSubmit">确 定</el-button>
        </div>
    </el-dialog>
  </el-dialog>
</template>
<script>
import { caseReport, pictureAlgorithmList, getTableHeader, characteristicPool, characteristicPoolAdd, getDetail, update} from "@/api/featureManager/reportCard";
export default {
  data() {
    // 区间输入校验规则
    const validateIsPositiveInteger= (rule, value, callback) => {
      const reg = /^(\-)?\d+(\.\d+)?$/
      if (!reg.test(value)) {
        return callback(new Error('只能输入数字'))
      } else {
        callback()
      }
    }
    return {
      dialogFormVisible: false,
      reportTemplateList: [],
      pictureAlgorithmList: [],
      featurePoolArray: [],
      featurePoolList: [],
      hasPool: false,
      busy: false,
      mainFrom: {
        report: '',
        isConfigAlgorithm: 0,
        pictureAlgorithm: '',
        featurePool: ''
      },
      mainRules: {
        report: [
          { required: true, message: '请选择报告单', trigger: 'change' }
        ],
        isConfigAlgorithm: [
          { required: true, message: '请选择是否配置算法', trigger: 'change' }
        ],
        pictureAlgorithm: [
          { required: true, message: '请选择图片算法', trigger: 'change' }
        ],
        featurePool: [
          { required: true, message: '请选择特征池', trigger: 'blur' }
        ]
      },
      tableHeader: [],
      tableData: [],
      page: 1,
      innerVisible: false,
      quotaFrom: {
        maxQuota: '',
        minQuota: ''
      },
      quotaRules: {
        maxQuota: [
          { required: true, message: '请输入最大值', trigger: 'blur' },
          { validator: validateIsPositiveInteger }
        ],
        minQuota: [
          { required: true, message: '请输入最小值', trigger: 'blur' },
          { validator: validateIsPositiveInteger }
        ]
      },
      currentFeatureId: '',
      currentHeaderCode: '',
      currentHeaderName: '',
      currenIndex: -1,
      currentMax: '',
      currentMin: '',
      submitLoading: false
    }
  },
  props: {
    title: String,
    currentId: String
  },
  methods: {
    // 获取报告单列表
    caseReportFun () {
      caseReport()
       .then(response => {
         this.reportTemplateList = response.data.data || []
       })
    },
    // 获取图片算法
    pictureAlgorithmListFun () {
      pictureAlgorithmList()
       .then(response => {
        this.pictureAlgorithmList = response.data.data || []
       })
    },
    // 根据报告单获取表头
    handleGetTableHeader () {
      this.tableData = []
      this.mainFrom.featurePool = ''
      this.tableHeader = []
      if(this.mainFrom.report) {
        getTableHeader(this.mainFrom.report)
         .then(response => {
           this.tableHeader =  response.data.data 
         })
      }
    },
    // 参数池数据
    characteristicPoolFun () {
      let ids = this.tableData.map(k => {
        return k.code
      })
      let params = {
        current: this.page,
        size: 20,
        ids: ids ? ids.join(',') : ''
      }
      characteristicPool(params)
       .then(response => {
        this.featurePoolList = this.featurePoolList.concat(response.data.data.records)
       })
    },
    // 隐藏弹窗
    hidePool () {
      this.hasPool = false
    },
    // 打开弹窗回调事件
    handleOpen () {
      this.caseReportFun()
      this.pictureAlgorithmListFun()
      if (this.currentId) { 
        getDetail(this.currentId).then(res => {
          let poolList = JSON.parse(JSON.stringify(res.data.data.mapList))
          let result = []
          if (poolList && poolList.length > 0) {
            result = poolList.map(k => {
              return k.name
            })
          }
          this.mainFrom = {
            report: res.data.data.caseReportId,
            isConfigAlgorithm: res.data.data.isPictureAlgorithm ? 1: 0,
            pictureAlgorithm: res.data.data.pictureAlgorithmId,
            featurePool: result.join(',')
          }
          this.tableHeader = res.data.data.tableHeadDataTypeVOS
          this.tableData = res.data.data.mapList
      })
      }
    },
    // 选择参数池
    choosePool () {
      this.hasPool = true
      this.page = 1
      this.featurePoolList = []
      setTimeout(() => {
        let box = this.$refs.box
        box.addEventListener('scroll', this.handleScroll, true)
      }, 500)
      this.characteristicPoolFun()
    },
    // 参数池加载更多
    handleScroll (e) {
      //变量scrollTop是滚动条滚动时，距离顶部的距离
      var scrollTop = e.target.scrollTop
      //变量windowHeight是可视区的高度
      var windowHeight = e.target.clientHeight
      //变量scrollHeight是滚动条的总高度
      var scrollHeight = e.target.scrollHeight
      //滚动条到底部的条件
      if(scrollTop + windowHeight == scrollHeight){
        this.page += 1
        this.characteristicPoolFun()
      }
    },
    // 取消特征池选择
    handleCancel () {
     this.hasPool = false
    },
    // 确定-特征池
    handleGetPool () {
     if (this.featurePoolArray.length > 0) {
      let list = []
      this.featurePoolArray.forEach(item => {
        let obj = {
          code: item.id,
          name: item.characteristicName,
          unit: item.unit
        }
        list.push(obj)
      })
       this.tableData = this.tableData.concat(list)
       // 遍历获取参数池名称
       let nameList = this.tableData.map((k) => {
        return k.name
       })
       this.$set(this.mainFrom, 'featurePool', nameList.reverse().join(','))
       this.$nextTick(() => {
          this.$refs['mainFrom'].clearValidate(['featurePool'])
       })
     }
     this.hasPool = false
     this.featurePoolArray = []
    },
    // 删除指标
    handleDelete (row, index) {
      this.tableData.splice(index, 1)
      let nameList = this.tableData.map((k) => {
        return k.name
      })
      this.$set(this.mainFrom, 'featurePool', nameList.reverse().join(','))
    },
    // 指标配置
    handleConfig (row, header, index) {
      if (header.isRange) {
        this.currentFeatureId = row.featureId
        this.currentHeaderCode = header.headCode
        this.currentHeaderName = header.headName
        this.currenIndex = index
        this.currentMax = row[header.headCode + '_max']
        this.currentMin = row[header.headCode + '_min']
        this.innerVisible = true
        this.quotaFrom = {
          maxQuota: this.currentMax,
          minQuota: this.currentMin
        }
        this.$nextTick(() => {
          this.$refs.quotaFrom.clearValidate()
        })
        this.hasPool = false
      }
    },
    // 关闭弹窗
    handleClose() {
      this.submitLoading = false
      this.tableData = []
      this.tableHeader = []
      this.mainFrom = {
        report: '',
        isConfigAlgorithm: 0,
        pictureAlgorithm: '',
        featurePool: ''
      }
      this.$refs.mainFrom.resetFields()
      this.dialogFormVisible = false
    },
    // 提交
    handleSubmitData() {
      this.submitLoading = true
      this.$refs.mainFrom.validate((valid) => {
          if (valid) {
              let reportInfo = this.reportTemplateList.filter(k => k.id === this.mainFrom.report)
              let params = {
                caseReportCode: reportInfo[0].value,
                caseReportId: this.mainFrom.report,
                caseReportName: reportInfo[0].label,
                isPictureAlgorithm: this.mainFrom.isConfigAlgorithm === 1,
                pictureAlgorithmId: this.mainFrom.pictureAlgorithm,
                characteristicPoolVOS: this.tableData
              }
              if (this.currentId) {
                update(Object.assign({}, params, {id: this.currentId}))
                 .then(() => {
                  this.$message.success('编辑成功')
                  this.handleClose()
                  this.$emit('getReportTemplateList')
                 })
                 .catch(() => {
                  this.submitLoading = false
                 })
              } else {
              characteristicPoolAdd(params)
               .then(() => {
                  this.$message.success('新增成功')
                  this.handleClose()
                  this.$emit('getReportTemplateList')
               })
               .catch(() => {
                  this.submitLoading = false
                 })
              }
          }
      })
    },
    // 取消指标配置
    handleQuotaClose () {
      this.quotaFrom = {
        maxQuota: '',
        minQuota: ''
      }
      this.currentFeatureId = ''
      this.currentHeaderCode = ''
      this.currentHeaderName = ''
      this.currenIndex = -1
      this.currentMax = ''
      this.currentMin = ''
      this.$refs.quotaFrom.clearValidate()
      this.innerVisible = false
    },
    // 提交指标配置
    handleQuotaSubmit () {
      this.$refs.quotaFrom.validate((valid) => {
          if (valid) {
            if (this.quotaFrom.maxQuota - this.quotaFrom.minQuota >= 0) {
              this.$set(this.tableData[this.currenIndex], this.currentHeaderCode  + '_max', this.quotaFrom.maxQuota)
              this.$set(this.tableData[this.currenIndex], this.currentHeaderCode  + '_min', this.quotaFrom.minQuota)
              this.handleQuotaClose()
            } else {
              this.$message.warning('最小值不能大于最大值!')
            }
          }
        })
    }
  }
};
</script>
  
<style scoped>
.featurePool-container {
  position: relative;
}
.featurePool-wrap {
  width: 240px;
  height: 300px;
  background: #F5F7FA;
  border-radius: 5px;
  position:absolute;
  top: 33px;
  left: 130px;
  z-index: 99999 !important;
}
.featurePool-list {
  padding: 10px;
  box-sizing: border-box;
  width: 100%;
  height: 250px;
}
.scroll-wrap {
  width: 100%;
  height: 100%;
  overflow-y: scroll;
  overflow-x: hidden;
}
.featurePool-bottom {
  position: absolute;
  bottom: 5px;
  right: 5px;
  text-align: right;
}
.norm-config {
 width: 100%;
}
.config-btn {
  display: block;
}
.config-color {
  color: #409EFF;
  font-size: 14px;
  cursor: pointer;
}
.el-checkbox {
  width: 100%;
}
.w-240 {
  width: 240px;
}
.el-form-item--small .el-form-item__content, .el-form-item--small .el-form-item__label {
  line-height: 20px !important;
}
.delete-btn {
  display: block;
  cursor: pointer;
  color: #409EFF;
}
/* .el-dialog__body {
  height: 400px !important;
  overflow-y: auto;
} */
</style>
  